# coding:utf-8
import time
from pathlib import Path
from shutil import copyfile

from PyQt5.QtGui import QTextCursor
from PyQt5.QtWidgets import QMainWindow, QMessageBox, QFileDialog

import SerialMonitor
import ui_serial_monitor
import setting_dialog


class SerialMonitorWindow(QMainWindow, ui_serial_monitor.Ui_MainWindow):  # 继承界面类及QMainWindow类
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.StartListen.triggered.connect(self.onClickStartListen)
        self.StopListen.triggered.connect(self.onClickStopListen)
        self.action.triggered.connect(self.onQuickListen)
        self.SaveSerialData.triggered.connect(self.onSaveClickListen)
        self.Clear.triggered.connect(self.clearClickListen)

        self.monitor: SerialMonitor.SerialMonitor
        self.physicalPortName = ""
        self.physicalPortRate = 0
        self.virtualPortName = ""
        self.virtualPortRate = 0
        self.isMonitor = False
        self.filename = ""

    def onClickStartListen(self):
        if self.isMonitor:
            self.monitor.Stop()

        dialog = setting_dialog.SettingDialog()
        dialog.exec_()
        if dialog.IsSetting:
            self.physicalPortName = dialog.getPhysicalPortName()
            self.physicalPortRate = int(dialog.getPhysicalPortRate())
            self.virtualPortName = dialog.getVirtualPortName()
            self.virtualPortRate = int(dialog.getVirtualPortRate())
            path = Path("./data")
            if not path.is_dir():
                path.mkdir()

            self.filename = "./data/trace_" + time.strftime("%Y%m%d%H%M%S", time.localtime()) + ".txt"
            self.monitor = SerialMonitor.SerialMonitor(
                self.filename, self.monitorMessage,
                dialog.getPhysicalPortName(), dialog.getPhysicalPortRate(),
                dialog.getVirtualPortName(), dialog.getVirtualPortRate())
            self.isMonitor = True
            self.textBrowser.setText("")
            self.monitor.Start()

    def onClickStopListen(self):
        self.isMonitor = False
        if self.monitor is not None:
            self.monitor.Stop()

    def onQuickListen(self):
        if len(self.physicalPortName)== 0 or len(self.virtualPortName) == 0:
            dialog = setting_dialog.SettingDialog()
            dialog.exec_()
            if dialog.IsSetting:
                self.physicalPortName = dialog.getPhysicalPortName()
                self.physicalPortRate = int(dialog.getPhysicalPortRate())
                self.virtualPortName = dialog.getVirtualPortName()
                self.virtualPortRate = int(dialog.getVirtualPortRate())
                path = Path("./data")
                if not path.is_dir():
                    path.mkdir()
                self.filename = "./data/trace_" + time.strftime("%Y%m%d%H%M%S", time.localtime()) + ".txt"
                self.monitor = SerialMonitor.SerialMonitor(
                    self.filename, self.monitorMessage,
                    dialog.getPhysicalPortName(), dialog.getPhysicalPortRate(),
                    dialog.getVirtualPortName(), dialog.getVirtualPortRate())
                self.textBrowser.setText("")
                self.monitor.Start()

        else:
            path = Path("./data")
            if not path.is_dir():
                path.mkdir()
            self.filename = "./data/trace_" + time.strftime("%Y%m%d%H%M%S", time.localtime()) + ".txt"
            self.monitor = SerialMonitor.SerialMonitor(
                self.filename, self.monitorMessage,
                self.physicalPortName, self.physicalPortRate,
                self.virtualPortName, self.virtualPortRate)
            self.textBrowser.setText("")
            self.monitor.Start()

    def onSaveClickListen(self):
        filename, filetype = QFileDialog.getSaveFileName(self, '保存文件', './data', "ALL (*.*)")
        if filename:
            if self.isMonitor:
                self.monitor.Stop()
                copyfile(self.filename, filename)

    def monitorMessage(self, message):
        self.textBrowser.append(message[:len(message)-1])
        self.textBrowser.moveCursor(QTextCursor.End)

    def clearClickListen(self):
        self.textBrowser.clear()
